package com.znxs.user_center_c.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.znxs.user_center_c.common.BaseResponse;
import com.znxs.user_center_c.common.ErrorCode;
import com.znxs.user_center_c.common.ResultUtils;
import com.znxs.user_center_c.exception.BusinessException;
import com.znxs.user_center_c.model.dto.UserLoginRequest;
import com.znxs.user_center_c.model.dto.UserRegisterRequest;
import com.znxs.user_center_c.model.dto.UserUpdateRequest;
import com.znxs.user_center_c.model.entity.User;
import com.znxs.user_center_c.model.vo.UserVO;
import com.znxs.user_center_c.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.znxs.user_center_c.contant.userContent.ADMIN_ROLE;
import static com.znxs.user_center_c.contant.userContent.USER_LOGIN_STATE;

/**
 * 用户接口
 *
 * @author znxs
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        // controller 校验倾向于请求本身的校验，不涉及业务逻辑
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            return ResultUtils.error(ErrorCode.NULL_ERROR);
        }
        long result = userService.userRegister(userRegisterRequest.getUserAccount(), userRegisterRequest.getUserPassword(), userRegisterRequest.getCheckPassword());
        return ResultUtils.success(result);
    }


    @GetMapping("/current")
    public BaseResponse<UserVO> getCurrent(HttpServletRequest request) {
        // 获取用户的状态
        UserVO userObj = (UserVO) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) throw new BusinessException(ErrorCode.NOT_LOGIN);
        Long id = userObj.getId();
        // todo 校验用户是否合法
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.SYS_ERROR, "用户不存在");
        }
        UserVO safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }

    @PostMapping("/login")
    public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        // controller 校验倾向于请求本身的校验，不涉及业务逻辑
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        UserVO userVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(userVO);

    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userOutLogin(HttpServletRequest request) {
        userService.outLogin(request);
        return ResultUtils.success("登录成功");
    }


    @GetMapping("/search")
    public BaseResponse<List<UserVO>> searchUser(@RequestParam(value = "userNickname", required = false) String userNickname, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "不为管理员");
        }
        // 搜索操作
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        // 不为空时在模糊查询
        if (StringUtils.isNotBlank(userNickname)) {
            userQueryWrapper.like("user_account", userNickname);
        }
        List<User> userList = userService.list(userQueryWrapper);
        List<UserVO> safeUserList = userList.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
        return ResultUtils.success(safeUserList);
    }

    @DeleteMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestParam long id, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "不为管理员");
        }
        if (id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 删除操作
        return ResultUtils.success(userService.removeById(id));
    }


    @PostMapping("/update/userStatus")
    public BaseResponse<Integer> updateUserStatus(@RequestParam int status, HttpServletRequest request) {
        int i = 0;
        if (status == 1) {
            i = userService.userRestore(request);
        }
        if (status == 0) {
            i = userService.userClose(request);
        }
        return ResultUtils.success(i);
    }

    @PostMapping("/update/userInfo")
    public BaseResponse<Integer> updateUserInfo(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        if (userUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        int i = userService.updateUserInfo(userUpdateRequest, request);
        return ResultUtils.success(i);
    }


    /**
     * 鉴权
     *
     * @param request http请求参数
     * @return 是否为管理员
     */
    public Boolean isAdmin(HttpServletRequest request) {
        // 获取登录态
        UserVO userObj = (UserVO) request.getSession().getAttribute(USER_LOGIN_STATE);
        // 鉴权 （不是管理员就静止调用）
        return userObj != null && userObj.getUserRole() == ADMIN_ROLE;
    }

}
